function get_rgb_box(x0,y0,x1,y1)
  local area=0 -- total area accumulated in pixels 
  local rsum,gsum,bsum = 0,0,0
  local x,y
  local xsize, ysize

  for y=math.floor(y0),math.ceil(y1) do
    ysize = 1.0
    if y<y0 then
      size = size * (1.0-(y0-y))
    end
    if y>y1 then
      size = size * (1.0-(y-y1))
    end
    for x=math.floor(x0),math.ceil(x1) do
      size = ysize
      r,g,b = get_rgb(x,y)
      if x<x0 then
        size = size * (1.0-(x0-x))
      end
      if x>x1 then
        size = size * (1.0-(x-x1))
      end
      rsum,gsum,bsum = rsum + r*size, gsum + g*size, bsum + b*size
      area = area+size
    end
  end
  
  return rsum/area, gsum/area, bsum/area
end

function scale(ratio)
  for y=0, (height*ratio)-1 do
    for x=0, (width*ratio)-1 do
      u0 = x * (1.0/ratio)
      v0 = y * (1.0/ratio)
      u1 = (x+1) * (1.0/ratio)
      v1 = (y+1) * (1.0/ratio)
      r,g,b=get_rgb_box(u0,v0,u1,v1)
      set_rgb(x,y,r,g,b)
    end
    progress (y/(height*ratio))
  end
  flush()
end

scale(0.33)